package com.example.cadmin.security.handler;

import com.alibaba.fastjson.JSON;
import com.example.cadmin.entity.LoginLog;
import com.example.cadmin.log.CabinetLog;
import com.example.cadmin.security.dto.JwtUserDto;
import com.example.cadmin.security.utils.JwtUtils;
import com.example.cadmin.service.CabinetLogService;
import com.example.cadmin.service.LoginLogService;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 张彬
 * @createTime 2023-2-23
 * 登录成功
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    public LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        JwtUserDto userDetails = (JwtUserDto) authentication.getPrincipal();//拿到登录用户信息
        String jwtToken = jwtUtils.generateToken(userDetails.getUsername());//生成token
        HttpSession session = httpServletRequest.getSession();
        //删除缓存里的验证码信息
//        session.removeAttribute("captcha");

        //修改编码格式
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json");
        //保存登录日志
//        LoginLog loginLog = new LoginLog();
//        loginLog.setUserName(userDetails.getUsername());
//        loginLog.setCreateTime(DateFormat.getTime());
//        loginLog.setType(1);
//        loginLogService.save(loginLog);
        //保存柜子日志
//        CabinetLog.insert(1, "用户 " + userDetails.getUsername() + " 登录成功", "");
        //将token写入到cookie中

        //输出结果
        httpServletResponse.getWriter().write(JSON.toJSONString(ResponseModel.success("登录成功")));

    }
}
